import { useState } from 'react'
import { motion } from 'framer-motion'
import { assessmentApi } from '../services/api'
import type { AssessmentResult, WeaknessAnalysis, StudyPlan } from '../types'
import './AssessmentPanel.css'

interface AssessmentPanelProps {
  userId: string
  onPlanCreated?: (planId: string) => void
}

const AssessmentPanel = ({ userId, onPlanCreated }: AssessmentPanelProps) => {
  const [assessmentResult, setAssessmentResult] = useState<AssessmentResult | null>(null)
  const [weaknessAnalysis, setWeaknessAnalysis] = useState<WeaknessAnalysis | null>(null)
  const [studyPlan, setStudyPlan] = useState<StudyPlan | null>(null)
  const [isLoading, setIsLoading] = useState(false)
  const [selectedPlanDays, setSelectedPlanDays] = useState<180 | 90 | 60>(180)

  // 初始能力评估
  const runInitialAssessment = async () => {
    setIsLoading(true)
    try {
      const result = await assessmentApi.initialAssessment({
        user_id: userId,
        test_questions: [], // 实际应该传入测试题目
      })
      setAssessmentResult(result)
    } catch (error) {
      console.error('Failed to run assessment:', error)
    } finally {
      setIsLoading(false)
    }
  }

  // 薄弱环节分析
  const analyzeWeaknesses = async () => {
    setIsLoading(true)
    try {
      const analysis = await assessmentApi.weaknessAnalysis(userId)
      setWeaknessAnalysis(analysis)
    } catch (error) {
      console.error('Failed to analyze weaknesses:', error)
    } finally {
      setIsLoading(false)
    }
  }

  // 创建学习计划
  const createStudyPlan = async () => {
    setIsLoading(true)
    try {
      const plan = await assessmentApi.createStudyPlan(selectedPlanDays, userId)
      setStudyPlan(plan)
      
      // 自动激活计划并开始学习
      try {
        const { dailyLearningApi } = await import('../services/api')
        await dailyLearningApi.activatePlan(plan.plan_id, userId)
        
        // 触发回调，切换到每日学习
        if (onPlanCreated) {
          onPlanCreated(plan.plan_id)
        } else {
          alert('学习计划已创建并激活！\n\n点击"每日学习"开始今日学习')
        }
      } catch (error) {
        console.error('激活计划失败:', error)
        // 即使激活失败，计划也已创建
        if (onPlanCreated) {
          onPlanCreated(plan.plan_id)
        }
      }
    } catch (error) {
      console.error('Failed to create study plan:', error)
      alert('创建学习计划失败，请稍后重试')
    } finally {
      setIsLoading(false)
    }
  }

  return (
    <div className="assessment-panel">
      <div className="assessment-actions">
        <motion.button
          whileHover={{ scale: 1.05 }}
          whileTap={{ scale: 0.95 }}
          className="action-button"
          onClick={runInitialAssessment}
          disabled={isLoading}
        >
          初始能力评估
        </motion.button>
        <motion.button
          whileHover={{ scale: 1.05 }}
          whileTap={{ scale: 0.95 }}
          className="action-button"
          onClick={analyzeWeaknesses}
          disabled={isLoading}
        >
          薄弱环节分析
        </motion.button>
      </div>

      {/* 评估结果 */}
      {assessmentResult && (
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          className="result-card"
        >
          <h2>初始能力评估结果</h2>
          <div className="scores-grid">
            <div className="score-item">
              <label>法律基础</label>
              <div className="score-bar">
                <div
                  className="score-fill"
                  style={{ width: `${assessmentResult.results.legal_basics}%` }}
                ></div>
                <span>{assessmentResult.results.legal_basics}分</span>
              </div>
            </div>
            <div className="score-item">
              <label>思维严谨性</label>
              <div className="score-bar">
                <div
                  className="score-fill"
                  style={{ width: `${assessmentResult.results.thinking_rigor}%` }}
                ></div>
                <span>{assessmentResult.results.thinking_rigor}分</span>
              </div>
            </div>
            <div className="score-item">
              <label>答题速度</label>
              <div className="score-bar">
                <div
                  className="score-fill"
                  style={{ width: `${assessmentResult.results.answer_speed}%` }}
                ></div>
                <span>{assessmentResult.results.answer_speed}分</span>
              </div>
            </div>
            <div className="score-item">
              <label>知识广度</label>
              <div className="score-bar">
                <div
                  className="score-fill"
                  style={{ width: `${assessmentResult.results.knowledge_breadth}%` }}
                ></div>
                <span>{assessmentResult.results.knowledge_breadth}分</span>
              </div>
            </div>
          </div>
        </motion.div>
      )}

      {/* 薄弱环节分析 */}
      {weaknessAnalysis && (
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          className="result-card"
        >
          <h2>薄弱环节分析</h2>
          <div className="weak-areas">
            {weaknessAnalysis.weak_areas.map((area, index) => (
              <div key={index} className="weak-area-item">
                <div className="area-header">
                  <span className="area-name">{area.area}</span>
                  <span className="area-priority">{area.priority}</span>
                </div>
                <div className="area-score">
                  <span>得分: {area.score}分</span>
                </div>
              </div>
            ))}
          </div>
          {weaknessAnalysis.recommendations.length > 0 && (
            <div className="recommendations">
              <h3>改进建议</h3>
              <ul>
                {weaknessAnalysis.recommendations.map((rec, index) => (
                  <li key={index}>{rec}</li>
                ))}
              </ul>
            </div>
          )}
        </motion.div>
      )}

      {/* 学习计划创建 */}
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        className="plan-card"
      >
        <h2>创建学习计划</h2>
        <div className="plan-options">
          <label>
            <input
              type="radio"
              value="180"
              checked={selectedPlanDays === 180}
              onChange={() => setSelectedPlanDays(180)}
            />
            180天标准计划
          </label>
          <label>
            <input
              type="radio"
              value="90"
              checked={selectedPlanDays === 90}
              onChange={() => setSelectedPlanDays(90)}
            />
            90天强化计划
          </label>
          <label>
            <input
              type="radio"
              value="60"
              checked={selectedPlanDays === 60}
              onChange={() => setSelectedPlanDays(60)}
            />
            60天冲刺计划
          </label>
        </div>
        <button
          className="create-plan-button"
          onClick={createStudyPlan}
          disabled={isLoading}
        >
          {isLoading ? '创建中...' : '创建学习计划'}
        </button>

        {studyPlan && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            className="plan-details"
          >
            <h3>计划详情</h3>
            <div className="plan-info">
              <p>
                <strong>计划时长:</strong> {studyPlan.duration_days}天
              </p>
              <p>
                <strong>每日学习时长:</strong> {studyPlan.daily_targets.study_hours}小时
              </p>
              <p>
                <strong>每日题目数量:</strong> {studyPlan.daily_targets.questions}题
              </p>
            </div>
            <div className="plan-phases">
              <h4>学习阶段</h4>
              {studyPlan.phases.map((phase) => (
                <div key={phase.phase} className="phase-item">
                  <span className="phase-name">{phase.name}</span>
                  <span className="phase-duration">{phase.duration}天</span>
                </div>
              ))}
            </div>
          </motion.div>
        )}
      </motion.div>
    </div>
  )
}

export default AssessmentPanel

